package com.angel.webapp.keyValue;

import java.util.Collection;
import java.util.HashMap;
import java.util.Map;

import javax.servlet.http.HttpServletRequest;

import com.angel.common.keyValue.KeyValue;
import com.angel.common.keyValue.KeyValueResult;

/**
 * @author William
 * @since 03/February/2009
 */
public class RequestKeyValueResult implements KeyValueResult{

    private Map<Object, String> mapParameters;

    public RequestKeyValueResult(HttpServletRequest req){
        super();
        mapParameters = new HashMap<Object, String>();
        for(Object key: req.getParameterMap().keySet()){
        	mapParameters.put(key, req.getParameter(key.toString()));
        }
    }

    public Object getResultFor(Object o) {
        return this.mapParameters.get(o);
    }

    @SuppressWarnings({"unchecked"})
    public <T> Collection<T> findAllResults() {
        return (Collection<T>) mapParameters.values();
    }

    @SuppressWarnings({"unchecked"})
    public <T> Collection<T> findAllKeys() {
        return (Collection<T>) mapParameters.keySet();
    }

    public Long resultSize() {
        return new Long(mapParameters.size());
    }

    public Boolean hasResult() {
        return this.resultSize() > 0;
    }

    public Boolean hasResultSize(Long aResultSize) {
        return this.resultSize().longValue() == aResultSize.longValue();
    }

    public void addKeyValueResult(KeyValueResult keyValueResult) {
        for(Object key: keyValueResult.findAllKeys()){
            mapParameters.put(key, keyValueResult.getResultFor(key).toString());
        }
    }

    public <T extends KeyValue> void addAll(Collection<T> ts) {
        for(KeyValue keyValue: ts){
            this.mapParameters.put(keyValue.getKey().toString(), keyValue.getValue().toString());
        }
    }

    public Boolean containsResultFor(Object o) {
        return this.getResultFor(o) != null;
    }

	public <T extends KeyValue> void addKeyValue(T keyValue) {
		this.addKeyValue(keyValue.getValue(), keyValue.getValue().toString());
	}

	public <T> void addKeyValue(T key, T value) {
		this.mapParameters.put(key, value.toString());
	}

	public <T> Boolean removeKeyValue(T key) {
		this.mapParameters.remove(key);
		return !this.containsResultFor(key);
	}

	public <T extends KeyValue> Boolean removeKeyValue(T key) {
		return this.removeKeyValue(key.getKey());
	}
}